# -*- coding: utf-8 -*-

'''
Created on May 16, 2011

@author: peterd
'''

import urllib,urllib2, sys
import time
from threading import Timer

from django.core.exceptions import ObjectDoesNotExist
import django.utils.simplejson as json, sys

from web.service.HttpReader import unescape

from mhd.models import MHD_Stop_Type, MHD_Link_Type, MHD_Link, MHD_Stop, MHD_Link_Stop, MHD_Link_Direction
from mhd.models import MHD_Link_Timetable_Wrkday_School, MHD_Link_Timetable_Wrkday_Noschool, MHD_Link_Timetable_Weekend, MHD_Link_Timetable_Delta 
from mhd.parser import MHD_LinkTimetableParser


# TODO: read from link.timetable_url
url = 'http://www.imhd.zoznam.sk/ba/index.php'


def socket_handler(fh):
    fh.close()


for mhd_link in MHD_Link.objects.all().order_by('name'):
    #if not mhd_link.name in ['79', '8', '80', '83', '84', '87', '88', '89', '9', '91', '92', '93', '94', '95', '96', '98', '99']:
    #if not mhd_link.name in ['20', '22', '23', '34']:
    #    continue
    print "fetching timetable of link %s" % mhd_link.name
    
    time.sleep(60)
    for direction in mhd_link.getDirections().itervalues():
        time.sleep(30)
        #print u"fetching timetable of link %s, direction %s" % (mhd_link.name, direction.direction)
        
        link_timetable = None
        
        retry = 3
        while retry > 0:        
            try:
                request = urllib2.Request('http://www.imhd.zoznam.sk/ba/index.php', urllib.urlencode(direction.getTimetableUrlParams()))
                response = urllib2.urlopen(request)
        
                # close socket if not data received within 30s
                t = Timer(30.0, socket_handler,[response])
                t.start()
        
                print "processing timetable of link %s" % mhd_link.name
                mhd_link_timetable_parser = MHD_LinkTimetableParser()
                link_timetable = mhd_link_timetable_parser.parse(unescape(response.read().decode('cp1250')), mhd_link, direction)     

                t.cancel()
                
                break            
            
            except urllib2.HTTPError, error:
                retry = retry - 1 
                time.sleep(5)
            
            except AttributeError:
                retry = retry - 1 
                time.sleep(5)

            except TypeError:
                retry = retry - 1 
                time.sleep(5)


        link_stop_base = None
        for mhd_link_stop in MHD_Link_Stop.objects.filter(link = mhd_link, direction = direction).order_by('stop_number'):
            
            if mhd_link_stop.stop_number == 1:
                MHD_Link_Timetable_Wrkday_School.objects.filter(link_stop = mhd_link_stop).delete()        
                for arrival in link_timetable['work_days_school']:             
                    mhd_link_timetable = MHD_Link_Timetable_Wrkday_School(link_stop = mhd_link_stop, arrival = arrival)
                    mhd_link_timetable.save() 
        
                MHD_Link_Timetable_Wrkday_Noschool.objects.filter(link_stop = mhd_link_stop).delete()        
                for arrival in link_timetable['work_days_noschool']:             
                    mhd_link_timetable = MHD_Link_Timetable_Wrkday_Noschool(link_stop = mhd_link_stop, arrival = arrival)
                    mhd_link_timetable.save() 
        
                MHD_Link_Timetable_Weekend.objects.filter(link_stop = mhd_link_stop).delete()        
                for arrival in link_timetable['weekend']:             
                    mhd_link_timetable = MHD_Link_Timetable_Weekend(link_stop = mhd_link_stop, arrival = arrival)
                    mhd_link_timetable.save()
                    
                link_stop_base = mhd_link_stop

                mhd_link_timetable_delta = None
                try:
                    mhd_link_timetable_delta = MHD_Link_Timetable_Delta.objects.get(link_stop_base = link_stop_base, stop = mhd_link_stop.stop)                    
                    mhd_link_timetable_delta.delta = 0                     
                except ObjectDoesNotExist:
                    try:
                        mhd_link_timetable_delta = MHD_Link_Timetable_Delta(link_stop_base = link_stop_base, stop = mhd_link_stop.stop, delta = 0)
                    except IndexError:
                        continue
                    except KeyError:
                        continue
                except KeyError:
                    continue
                mhd_link_timetable_delta.save()
                
            else:
                mhd_link_timetable_delta = None
                try:
                    mhd_link_timetable_delta = MHD_Link_Timetable_Delta.objects.get(link_stop_base = link_stop_base, stop = mhd_link_stop.stop)                    
                    mhd_link_timetable_delta.delta = link_timetable['stops'][mhd_link_stop.stop.name]['delta_min']                     
                except ObjectDoesNotExist:
                    try:
                        mhd_link_timetable_delta = MHD_Link_Timetable_Delta(link_stop_base = link_stop_base, stop = mhd_link_stop.stop, delta = link_timetable['stops'][mhd_link_stop.stop.name]['delta_min'])
                    except IndexError:
                        continue
                    except KeyError:
                        continue
                except KeyError:
                    continue
                mhd_link_timetable_delta.save()
    
            try:
                mhd_link_stop.stop.zone = link_timetable['stops'][mhd_link_stop.stop.name]['zone']
                mhd_link_stop.stop.save()
            except KeyError:
                pass
                
            
